package com.lej.app_main.unity.pay

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.lej.app_main.mainService
import com.lej.core.utils.extention.logD
import com.lej.dataservice.club.bean.main.unity.U3dWxPayInfo
import com.lej.dataservice.club.http.checkData
import com.lej.dataservice.club.http.handleMsg
import com.lej.pay.utils.PayUtils
import com.lej.wx.data.WxStatus
import kotlinx.coroutines.launch

//unity支付中间页面
class UnityPayActivity : AppCompatActivity() {
    private var isSetRes = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val orderId = intent.getIntExtra(U3DConst.ORDER_ID, -1)
        orderWxPay(orderId)
    }

    private fun orderWxPay(orderId: Int) {
        lifecycleScope.launch {
            runCatching {
                mainService.gameOrderPay(orderId, U3DConst.WX_PAY).checkData()
            }.onFailure {
                it.handleMsg?.logD("-----------sss")
                payRes(U3DConst.WX_ERROR)
            }.getOrNull()?.wxPay()
        }
    }

    private fun U3dWxPayInfo.wxPay() {//调起支付
        PayUtils.wxPay(
            context = this@UnityPayActivity,
            appId = this.appid,
            partnerId = this.partnerid,
            prepayId = this.prepayid,
            noncestr = this.nonceStr,
            timestamp = this.timeStamp,
            paySign = this.sign
        ) { status, _ ->
            payRes(
                when (status) {
                    WxStatus.WX_OK -> U3DConst.WX_OK
                    WxStatus.WX_CANCEL -> U3DConst.WX_CANCEL
                    WxStatus.WX_ERROR -> U3DConst.WX_ERROR
                }
            )
        }
    }

    override fun onBackPressed() {
        setStatus(U3DConst.WX_CANCEL)
        super.onBackPressed()
    }

    private fun payRes(@PayType payStatus: Int) {
        setStatus(payStatus)
        super.finish()
    }

    override fun finish() {
        setStatus(U3DConst.WX_CANCEL)
        super.finish()
    }

    private fun setStatus(@PayType payStatus: Int) {
        if (isSetRes) return
        isSetRes = true
        setResult(RESULT_OK, Intent().apply {
            putExtra(U3DConst.PAY_STATUS_KEY, payStatus)
        })
    }
}